﻿using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using XRM.Security.DataAccess.Enums;
using XRM.Security.DataAccess.Helpers;
using XRM.Security.DataAccess.Models;
using XRM.Security.WebUI.Enums;
using XRM.Security.WebUI.Helpers;
using XRM.Security.WebUI.Models.WorkKind;

namespace XRM.Security.WebUI.Controllers
{
    [System.Web.Mvc.Authorize]
    public class WorkKindController : BaseController
    {
        [System.Web.Mvc.Authorize(Roles = "Administrator, WorkKindViewer, WorkKindEditor")]
        public ActionResult Index()
        { 
            var workKinds = WorkKindRepository.GetAll().Actual()
                .Select(s => new WorkKindModel
                    {
                        Id = s.WorkKindId,
                        Name = s.WorkKindName,
                        Description = s.Description,
                        IsFixed = s.IsFixed,
                        IsLinkedWithSign = s.IsLinkedWithSign
                    }).ToList();
            return View(workKinds);
        }
        
        [System.Web.Mvc.HttpGet]
        [System.Web.Mvc.Authorize(Roles = "Administrator, WorkKindViewer, WorkKindEditor")]
        public ActionResult Edit(int? id)
        {
            WorkKindModel model = new WorkKindModel(id != null ? WorkKindRepository.Get(id) : null, WorkKindParamRepository.GetAll().OrderBy(x => x.WorkKindParamName).ToList());
            if ((id != null) && (model.Id == null))
                throw new HttpException(404, "Вид работ не найден");
            else if ((id == null) && (!Permission.AllowWorkKindEdit()))
                throw new HttpException(404, "Вид работ не найден");

            SetParamCanDelete(model);
            model.ReadOnly = !Permission.AllowWorkKindEdit();

            return View(model);
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize(Roles = "Administrator, WorkKindEditor")]
        public ActionResult Edit(WorkKindModel model)
        {
            foreach (var item in model.ParamList)
            {
                item.Name = WorkKindParamRepository.Get(item.Id).WorkKindParamName;
            }
            model.GetParamAll(WorkKindParamRepository.GetAll().OrderBy(x => x.WorkKindParamName).ToList());
            SetParamCanDelete(model);

            if (!ModelState.IsValid)
            {
                return View(model);
            }

            WorkKind workKind;
            if (model.IsEdit)
            {
                workKind = WorkKindRepository.Get(model.Id);
                if (workKind == null)
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            else
            {
                workKind = new WorkKind();
            }

            model.ApplyChanges(workKind);

            if (model.IsEdit)
            {
                WorkKindRepository.Update( workKind );
                ShowAlert(AlertType.Success, "Вид работ успешно отредактирован.");
            }
            else
            {
                WorkKindRepository.Add( workKind );
                ShowAlert(AlertType.Success, "Вид работ успешно добавлен.");
            }
            return RedirectToAction("Index");
        }

        [System.Web.Mvc.Authorize(Roles = "Administrator, WorkKindEditor")]
        public ActionResult Delete(int id)
        {
            var workKind = WorkKindRepository.Get(id);
            if (workKind == null || workKind.IsFixed)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            if ( RequestRepository.GetAll().Any( s => ( s.Status == (int)RequestStatus.InWork || s.Status == (int)RequestStatus.InPart ) &&
                s.RequestWorkKinds.Any( g => g.WorkKindId == id ) ) )
            {
                ShowAlert( AlertType.Error, "Не удалось удалить вид работ, т.к. он используется в открытой заявке." );
            }
            else
            {
                workKind.IsDeleted = true;
                WorkKindRepository.Update( workKind );
                ShowAlert( AlertType.Success, "Вид работ успешно удален." );
            }
            return RedirectToAction("Index");
        } 

        [System.Web.Mvc.NonAction]
        private void SetParamCanDelete(WorkKindModel model)
        {
            model.AllowParamCRUD = (!RequestRepository.GetAll(x => (x.Status != (int)RequestStatus.Error) && x.RequestWorkKinds.Where(wx => (!wx.CloseDate.HasValue) && (wx.WorkKindId == model.Id)).Any()).Any()) && (!model.IsFixed);
        }
    }
}
